package com.ajie.controller;


import com.ajie.service.SysUserService;
import com.ajie.utils.*;
import com.ajie.vo.MailVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Random;

/**
 * 发送工具控制器
 */
@RestController
@RequestMapping("/tool")
@Slf4j
public class SendsController  {
    
    @Autowired
    private QiniuUtils qiniuUtils;
    
    @Autowired
    private MailUtils mailUtils;
    
    @Autowired
    private SysUserService userService;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private SMSUtils smsUtils;
    
    @Autowired
    private RedisUtil redisUtil;
    
    
    @ApiOperation(value="七牛云上传头像")
    @PostMapping("/upload")
    public Result upload(@RequestBody MultipartFile file) throws IOException {
        log.info("该文件名是：SendsController,该方法是：upload");
        String url = qiniuUtils.uploadQiniu(file.getBytes(), file.getOriginalFilename());
        log.info("获取文件路径为-》{}",url);
        
        return Result.success("上传文件成功！",url);
    }
    
    
    @ApiOperation(value="忘记密码？邮件找回")
    @PostMapping("/forget/password")
    public Result forget(@RequestBody MailVo mail){
        log.info("该文件名是：SendsController,该方法是：forget");
        mail.setSubject("农业教育云平台");
        Random random = new Random();
        int password =  100000+random.nextInt(1000000);
        userService.updatePwdByMail(mail.getReceivers()[0],passwordEncoder.encode(MD5Utils.md5(String.valueOf(password))));
        mail.setContent("您的新密码："+ password +"，请妥善保管");
        return Result.success(mailUtils.sendMail(mail));
    }
    
    @ApiOperation(value="给手机发送验证码")
    @PostMapping("/sms")
    public Result sendSms(String phoneNumber){
        log.info("该文件名是：SendsController,该方法是：sendSms");
        Random random = new Random();
        int code = 100000 +  random.nextInt(899999);
//        smsUtils.sendSms(phoneNumber,code);
        redisUtil.setValueTime(phoneNumber + "sms", code , 5);
        return Result.success("验证码发送成功！");
        
    }
    
    
    
    
    
    
    
}
